/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epam.expertsys.dbconn;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 *
 * @author Admin
 */
public class GenericDAOH2 {

    protected final int MAX_CONN_COUNT;
    protected JdbcConnectionPool conPool;
    final private static Properties dbProps = new Properties();
    private static String login = "";
    private static String pass = "";
    private static String url = "";

    static {
        try {
            dbProps.load(GenericDAOH2.class.getResourceAsStream("/dbProperties.properties"));
            login = dbProps.getProperty("db.login");
            pass = dbProps.getProperty("db.password");
            url = dbProps.getProperty("db.url");

        } catch (IOException e) {
        }
        //    System.out.println(url);
    }

    public GenericDAOH2(int maxConnCount) throws SQLException {
        this.MAX_CONN_COUNT = maxConnCount;
    }

    public void start() throws SQLException {
        conPool = createPool();
        conPool.setMaxConnections(MAX_CONN_COUNT);
    }

    public void stop() throws SQLException {
        conPool.dispose();
    }

    public Connection getConnection() throws SQLException {
        return conPool.getConnection();
    }

    protected JdbcConnectionPool createPool() throws SQLException {
        //TODO: transfer hard-coded connection parameters to properties


        return JdbcConnectionPool.create(url, login, pass);


        /*return JdbcConnectionPool.create(
        "jdbc:h2:d:\\ourprojects\\epam\\korolevich_expertsys\\MedicalDB",
        "sa", "");*/
    }

    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("Connection closure error");
            }
        }
    }

    protected void closeStatement(PreparedStatement myStat) {
        if (myStat != null) {
            try {
                myStat.close();
            } catch (SQLException e) {
                System.out.println("Statement closure error");
            }
        }
    }
}
